package com.bcx.wind.workflow.access.paging;

import com.bcx.wind.workflow.db.tran.WindTransactionManager;
import com.bcx.wind.workflow.exception.WorkflowException;

import java.sql.Connection;
import java.sql.SQLException;

import static com.bcx.wind.workflow.access.DbPro.*;
import static com.bcx.wind.workflow.support.ObjectHelper.hasValue;

/**
 * 数据库层相关工具
 *
 * @author zhanglei
 */
public class PagingBuilder {


    /**
     * 通过连接查询连接是属于那种数据库
     * 并获取该数据库的分页插件返回
     *
     * @param connection  数据库连接
     * @return             分页插件
     */
    public static Paging  buildPaging(Connection connection){
        Paging paging = null;
        try {
            String productName = connection.getMetaData().getDatabaseProductName();
            String relName = productName.toLowerCase().replaceAll(" ","")
                    .replaceAll("_","");

            if(hasValue(relName,DB2)){
                paging =  new Db2Paging();
            }else if(hasValue(relName,POSTGRESQL)){
                paging =   new PostgresPaging();
            }else if(hasValue(relName,H2)){
                paging =   new H2Paging();
            }else if(hasValue(relName,ORACLE)){
                paging =   new OraclePaging();
            }else if(hasValue(relName,MARIADB)){
                paging =  new MariaPaging();
            }else if(hasValue(relName,MYSQL)){
                paging =   new MySqlPaging();
            }else if(hasValue(relName,SQLSERVER)){
                paging =   new SqlServerPaging();
            }else{
                throw new WorkflowException("sorry! wind_workflow does not support this database for the time being: "+productName);
            }

        } catch (SQLException e) {
            e.printStackTrace();
            throw new WorkflowException("sorry! get database name error ,because "+e.getMessage());
        }
        try {
            WindTransactionManager.getInstance().removeConnection();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return paging;
    }




}
